package com.liangge.essaysite.util;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtils {
	private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
	private static HttpClient httpclient;
	static {
		HttpParams params = new BasicHttpParams();
    	HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    	//设置连接超时
    	HttpConnectionParams.setConnectionTimeout(params, 15*1000);
    	
    	PoolingClientConnectionManager manager = new PoolingClientConnectionManager();
    	//设置最大连接数
    	manager.setMaxTotal(50);
    	//设置每条通道最大并发连接数
    	manager.setDefaultMaxPerRoute(20);
    	httpclient = new DefaultHttpClient(manager,params);
	}

	/**
	 * get请求3次
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String httpGet(String url) {
		HttpGet httpget = new HttpGet(url);
		httpget.setHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7 360EE");
//		httpget.setHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
		// httpget.setHeader("Accept-Encoding", "gzip,deflate,sdch");
		httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
		String html = null;
		for (int i = 0; i < 2; i++) {
			HttpEntity httpEntity = null;
			try {
				HttpResponse response = httpclient.execute(httpget);
				httpEntity = response.getEntity();
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK && httpEntity != null) {
					html = EntityUtils.toString(httpEntity, "UTF-8");
					return html;
				}
			} catch (Exception e) {
				logger.error("第{}次请求失败,开始重连", i + 1);
				logger.error(e.getMessage(), e);
			} finally {
				try {
					EntityUtils.consume(httpEntity);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		httpget.abort(); // 关闭连接
		return html;
	}

	/**
	 * post请求
	 * 
	 * @return
	 */
	public static String post(String url, Map<String, String> map) {
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for (String key : map.keySet()) {
			NameValuePair nvp = new BasicNameValuePair(key, map.get(key));
			nvps.add(nvp);
		}
		String html = null;
		try {
			HttpPost httppost = new HttpPost(url);
			httppost.setEntity(new UrlEncodedFormEntity(nvps,"GB2312"));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity httpEntity = response.getEntity();
			System.out.println(response.getStatusLine().getStatusCode());
			System.out.println(EntityUtils.toString(httpEntity, "GBK"));
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK && httpEntity != null) {
				html = EntityUtils.toString(httpEntity, "GBK");
				EntityUtils.consume(httpEntity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return html;
	}
}
